/**
 * 密码修改接口测试用例
 *
 * Created by snowingsea on 2020/02/03.
 */
const randomstring = require('randomstring');
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../common');
const Administrator = require('./../../models/administrator');
const uri = require('./../uri');

module.exports = describe('/PUT me/password.json', function () {
  const url = '/me/password.json';
  const administrator = new Administrator();
  const newUserIds = [];
  let user = {};

  before(function (done) {
    administrator.createRandomUser()
      .then((res) => {
        user = res;
        newUserIds.push(user.userId);
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');

  // 正常请求
  it('it should CHANGE my password', function (done) {
    user.login()
      .then(() => {
        const newPassword = randomstring.generate(40);
        chai.request(uri)
          .put(url)
          .set('Authorization', `Bearer ${user.token.accessToken}`)
          .send({ oldPassword: user.password, newPassword })
          .end((err, res) => {
            res.should.have.status(200);
            user.password = newPassword;
            user.login()
              .then(() => {
                done();
              })
              .catch(done);
          });
      })
      .catch(done);
  });

  // 密码不正确
  it('it should fail to change password when the old password is not correct', function (done) {
    user.login()
      .then(() => {
        chai.request(uri)
          .put(url)
          .set('Authorization', `Bearer ${user.token.accessToken}`)
          .send({ oldPassword: randomstring.generate(40), newPassword: randomstring.generate(40) })
          .end((err, res) => {
            res.should.have.status(400);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
